/**
 * @author		Vinson
 * @time        2025-2-14下午5:53:58
 * @version     1.0.0
 */
class Timer extends EventTarget {
    constructor(delay, repeatCount = 0) {
        super();

        if (delay <= 0) {
            throw new Error('delay must be a positive number');
        }
        if (repeatCount < 0) {
            throw new Error('repeatCount must be a non-negative number');
        }

        this.delay = delay;
        this.repeatCount = repeatCount;
        this._currentCount = 0;
        this._isRunning = false;
        this._isPaused = false;
        this.intervalId = null;
    }

    start() {
        if (this._isRunning) {
            return;
        }

        this._isRunning = true;
        this._isPaused = false;

        // 如果是从暂停状态恢复，保持之前的计数
        if (this._currentCount === 0 && this.intervalId === null) {
            this._currentCount = 0;
        }

        this.intervalId = setInterval(() => {
            this._currentCount++;
            this._triggerTimerEvent();

            if (this.repeatCount !== 0 && this._currentCount >= this.repeatCount) {
                this._triggerCompleteEvent();
                this.stop();
            }
        }, this.delay);
    }

    stop() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
            this._isRunning = false;
            this._isPaused = false;
        }
    }

    reset() {
        this.stop();
        this._currentCount = 0;
        this._isRunning = false;
        this._isPaused = false;
    }

    pause() {
        if (this._isRunning && !this._isPaused) {
            clearInterval(this.intervalId);
            this.intervalId = null;
            this._isRunning = false;
            this._isPaused = true;
        }
    }

    resume() {
        if (!this._isRunning && this._isPaused) {
            this.start();
        }
    }

    updateRepeatCount(newRepeatCount) {
        if (newRepeatCount < 0) {
            throw new Error('repeatCount must be a non-negative number');
        }
        this.repeatCount = newRepeatCount;
    }

    _triggerTimerEvent() {
        const event = new Event('timer');
        this.dispatchEvent(event);
    }

    _triggerCompleteEvent() {
        const event = new Event('complete');
        this.dispatchEvent(event);
    }

    get currentCount() {
        return this._currentCount;
    }
}

// 导出 Timer 类
export default Timer;


// import Timer from './Timer.js';
//
// // 创建一个定时器，间隔 1 秒，触发 5 次
// const myTimer = new Timer(1000, 5);
// // 监听 timer 事件
// myTimer.addEventListener('timer', () => {
//     console.log('定时器触发: ' + myTimer.currentCount);
// });
//
// // 监听 complete 事件
// myTimer.addEventListener('complete', () => {
//     console.log('定时器完成!');
// });
//
// // 启动定时器
// myTimer.start();
//
// // 修改触发次数为 15
// myTimer.updateRepeatCount(15);
//
// // 暂停定时器
// myTimer.pause();
//
// // 恢复定时器
// myTimer.resume();